package day15.HomeWork;

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

public class ChinaTelecomSystem {
    static Scanner sc = new Scanner(System.in);
    static DecimalFormat df = new DecimalFormat("#.##");
    static Random r = new Random();
    static List<Scene> scenes = new ArrayList<>();
    static List<ConsumInfo> consumInfoList = new ArrayList<>();
    static Map<String, MobileCard> card = new HashMap<>();
    static Map<String, List<ConsumInfo>> consumInfo = new HashMap<>();
    static List<ServicePackage> spList = new ArrayList<>();
    static ServicePackage sp = null;
    static ConsumInfo cf = null;
    static MobileCard mc = null;

    static {
        inputMapConsum();
        inputCard();
    }

    public static void main(String[] args) {
        spList.add(new TalkPackage(58, 500, 30, 0));
        spList.add(new SuperPackage(78, 200, 50, 10));
        spList.add(new NetPackage(68, 0, 0, 30));
        menu1();
    }

    private static void menu1() {
        while (true) {
            System.out.println("=============欢迎使用中国电信系统=============");
            System.out.println("1.用户登录\t2.用户注册\t3.使用中国电信电话卡\t4.话费充值\t5.资费说明\t6.退出系统");
            String n = sc.next();
            try {
                int choice = Integer.parseInt(n);
                if (choice < 1 || choice > 6) {
                    System.out.println("输入错误,请输入1-6之间的数字");
                    continue;
                }
                switch (choice) {
                    case 1:
                        login();
                        break;
                    case 2:
                        reg();
                        break;
                    case 3:
                        useCard();
                        break;
                    case 4:
                        addMoney();
                        break;
                    case 5:
                        showTariff();
                        break;
                    case 6:
                        return;
                }
            } catch (NumberFormatException e) {
                System.out.println("输入错误,请输入数字");
            }
        }
    }

    public static void login() {
        boolean b = true;
        System.out.println("请输入电话号码");
        String phone = sc.next();
        System.out.println("请输入密码");
        String password = sc.next();

        // 先检查用户是否存在
        for (String s : card.keySet()) {
            if (s.contains(phone)) {
                b = false;
                break;
            }
        }

        // 再验证登录
        if (card.containsKey(phone) && password.equals(card.get(phone).getPassWord())) {
            System.out.println("登录成功");
            mc = card.get(phone);
            sp = card.get(phone).getSerPackage();

            // 使用副本避免并发修改
            List<ConsumInfo> tempList = new ArrayList<>();
            if (consumInfo.containsKey(phone)) {
                tempList.addAll(consumInfo.get(phone));
            }
            consumInfoList = tempList;

            menu2();
        }
        if (b) {
            System.out.println("用户不存在,请注册");
        }
    }

    public static void reg() {
        System.out.println("请输入电话号码的编号");
        String[] phones = randomPhone();
        for (int i = 0; i < phones.length; i++) {
            System.out.print((i + 1) + "." + phones[i] + "\t");
            if ((i + 1) % 3 == 0) {
                System.out.println();
            }
        }
        String phone = "";
        while (true) {
            try {
                int n = sc.nextInt();
                if (n < 1 || n > phones.length) {
                    System.out.println("输入错误，请输入1-" + phones.length + "之间的数字");
                    continue;
                }
                phone = phones[n - 1];
                break;
            } catch (InputMismatchException e) {
                System.out.println("输入错误，请输入数字");
                sc.next();
            }
        }
        System.out.println("请输入姓名");
        String name = sc.next();
        System.out.println("请输入密码");
        String password = sc.next();
        System.out.print("请输入你充值的话费:");
        int money = 0;
        while (true) {
            try {
                money = sc.nextInt();
                if (money < 0) {
                    System.out.print("请输入正确的数字:");
                    continue;
                }
                break;
            } catch (Exception e) {
                System.out.println("输入错误,请输入数字");
                sc.next();
            }
        }
        System.out.println("请选择购买的套餐");
        System.out.println("1.话痨套餐\t2.超人套餐\t3.网虫套餐");
        int m = 0;
        while (true) {
            try {
                m = sc.nextInt();
                if (m < 1 || m > 3) {
                    System.out.println("输入错误,请输入1-3");
                } else break;
            } catch (Exception e) {
                System.out.println("输入错误,请输入1-3");
                sc.next();
            }
        }
        switch (m) {
            case 1:
                sp = new TalkPackage(58, 500, 30, 0);
                break;
            case 2:
                sp = new SuperPackage(78, 200, 50, 10);
                break;
            case 3:
                sp = new NetPackage(68, 0, 0, 30);
                break;
        }
        while (money < sp.price) {
            System.out.println("你的话费不足以购买此套餐,请充值话费!(此套餐需要" + df.format(sp.price) + "一个月)");
            int addMon = 0;
            while (true) {
                try {
                    addMon = sc.nextInt();
                    if (addMon < 0) {
                        System.out.println("请输入正确的数字");
                        continue;
                    }
                    break;
                } catch (Exception e) {
                    System.out.println("请输入数字");
                }
            }
            money += addMon;
        }
        System.out.println("注册成功");
        mc = new MobileCard(phone, name, password, sp, sp.price, money - sp.price);
        mc.showMeg();
        card.put(phone, mc);
        outputCard();
        outputMapConsum();
        // }
    }

    public static void buyService(int m) {
        while (true) {
            if (m < 1 || m > 3) {
                try {
                    System.out.println("输入错误,请输入1-3");
                    m = sc.nextInt();
                } catch (InputMismatchException e) {
                    System.out.println("输入错误,请输入1-3");
                }
            } else break;
        }
        //spList.get(m - 1);
        switch (m) {
            case 1:
                sp = new TalkPackage(58, 500, 30, 0);
                break;
            case 2:
                sp = new SuperPackage(78, 200, 50, 10);
                break;
            case 3:
                sp = new NetPackage(68, 0, 0, 30);
                break;
        }
        while (mc.getMoney() < sp.price) {
            System.out.println("你的话费不足以购买此套餐,请充值话费!(此套餐需要" + df.format(sp.price) + "一个月,剩余:" + df.format(mc.getMoney()) + "元)");
            System.out.print("请输入充值的金额:");
            int addMon = 0;
            while (true) {
                try {
                    addMon = sc.nextInt();
                    if (addMon < 0) {
                        System.out.println("请输入正确的数字");
                        continue;
                    }
                    break;
                } catch (Exception e) {
                    System.out.println("输入错误,请输入数字");
                    sc.next();
                }
            }
            mc.setMoney(mc.getMoney() + addMon);
        }
        mc.setConsumAmount(mc.getConsumAmount() + sp.price);
        mc.setSerPackage(sp);
        mc.setMoney(mc.getMoney() - sp.price);
        mc.showMeg();
        card.put(mc.getCardNumber(), mc);
        outputCard();
        outputMapConsum();
    }

    public static void useCard() {
        int x1 = r.nextInt(100) + 1;
        int x2 = r.nextInt(100) + 1;
        int x3 = r.nextInt(3) + 1;
        Scene s1 = new Scene("打电话", x1, "跟客户打电话花了" + x1 + "分钟");
        Scene s2 = new Scene("发消息", x2, "跟朋友聊天,一共发了" + x2 + "条消息");
        Scene s3 = new Scene("上网", x3, "上网一共花了" + x3 + "GB");
        scenes.add(s1);
        scenes.add(s2);
        scenes.add(s3);
        System.out.println("请输入电话号码");
        String phone = null;
        while (true) {
            try {
                phone = sc.next();
                mc = card.get(phone);
                sp = card.get(phone).getSerPackage();
                break;
            } catch (Exception e) {
                System.out.println("输入错误,请重新输入");
            }
        }
        if (card.containsKey(phone)) {
            int i = Math.abs(r.nextInt()) % scenes.size();
            Scene scene = scenes.get(i);
            if (!consumInfo.containsKey(phone)) {
                consumInfoList = new ArrayList<>();
            }
            if (scene.getType().equals("打电话")) {
                System.out.println(scene.getDescription());
                sp.call(scene.getData(), card.get(phone));
                cf = new ConsumInfo(phone, scene.getType(), scene.getData());
                consumInfoList.add(cf);
                consumInfo.put(phone, consumInfoList);
            } else if (scene.getType().equals("发消息")) {
                System.out.println(scene.getDescription());
                sp.send(scene.getData(), card.get(phone));
                cf = new ConsumInfo(phone, scene.getType(), scene.getData());
                /*if (consumInfo.containsKey(phone)) {
                    consumInfoList.add(cf);
                    consumInfo.put(phone, consumInfoList);
                } else {
                    consumInfoList = new ArrayList<>();*/
                consumInfoList.add(cf);
                consumInfo.put(phone, consumInfoList);
                // }
            } else if (scene.getType().equals("上网")) {
                System.out.println(scene.getDescription());
                sp.netPlay(scene.getData(), card.get(phone));
                cf = new ConsumInfo(phone, scene.getType(), scene.getData());
                consumInfoList.add(cf);
                consumInfo.put(phone, consumInfoList);
            }
            outputCard();
            outputMapConsum();
        } else {
            System.out.println("电话号码不存在,请重新输入");
        }

    }

    public static void addMoney() {
        System.out.println("请输入你要充值的电话卡号码");
        String p = sc.next();
        for (String s : card.keySet()) {//card.containsKey(p);
            if (card.containsKey(p)) {
                System.out.println("请输入你要充值的金额");
                double n = 0;
                while (true) {
                    try {
                        n = sc.nextDouble();
                        if (n < 0) {
                            System.out.println("请充值正确的数字");
                            continue;
                        }
                        break;
                    } catch (InputMismatchException e) {
                        System.out.println("输入错误,请输入数字.");
                        sc.next();
                    }
                }
                double money = card.get(s).getMoney();
                card.get(s).setMoney(money + n);
                System.out.println("当前话费还有:" + df.format(card.get(s).getMoney()));
                return;
            } else {
                System.out.println("电话号码不存在请注册!");
                return;
            }
        }
        outputCard();
        outputMapConsum();
    }

    public static void showTariff() {
        File f = new File("d://wuxi.D//一阶段项目//资费说明.txt");
        if (f.exists()) {
            try {
                FileInputStream fis = new FileInputStream(f);
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void printAll() {
        try (FileOutputStream fos = new FileOutputStream("d://wuxi.D//一阶段项目//" + mc.getCardNumber() + "消费清单.txt");
             OutputStreamWriter osw = new OutputStreamWriter(fos);
             BufferedWriter bw = new BufferedWriter(osw);
        ) {
            bw.write("序号\t 类型\t 数据(通话(分钟)/上网(GB)/短信(条))");
            for (int i = 0; i < consumInfo.get(mc.getCardNumber()).size(); i++) {
                bw.newLine();
                bw.write((i + 1) + " \t " + consumInfo.get(mc.getCardNumber()).get(i).type + " \t " + consumInfo.get(mc.getCardNumber()).get(i).consumData);
            }
            bw.newLine();
            bw.write(mc.getSerPackage().showInfo());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            System.out.println("暂时还没有消费");
        }

        try (FileInputStream fis = new FileInputStream("d://wuxi.D//一阶段项目//" + mc.getCardNumber() + "消费清单.txt");
             InputStreamReader isr = new InputStreamReader(fis);
             BufferedReader br = new BufferedReader(isr);
        ) {
            System.out.println("*******" + mc.getCardNumber() + "的消费记录*******");
            //System.out.println("序号\t类型\t数据(通话(分钟)/上网(GB)/短信(条))");
            String msg = "";
            while ((msg = br.readLine()) != null) {
                System.out.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void outputCard() {
        try {
            File f = new File("d://wuxi.D//一阶段项目//手机信息.txt");
            if (!f.exists()) {
                f.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(f);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(card);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void inputCard() {
        try {
            FileInputStream fis = new FileInputStream("d://wuxi.D//一阶段项目//手机信息.txt");

            ObjectInputStream ois = new ObjectInputStream(fis);
            card = (Map<String, MobileCard>) ois.readObject();
        } catch (FileNotFoundException e) {

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void inputMapConsum() {
        try {
            FileInputStream fis = new FileInputStream("d://wuxi.D//一阶段项目//消费集合.txt");
            ObjectInputStream ois = new ObjectInputStream(fis);
            consumInfo = (Map<String, List<ConsumInfo>>) ois.readObject();
            System.out.println("数据加载成功!!!");
        } catch (FileNotFoundException e) {
            System.out.println("欢迎第一次使用");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void outputMapConsum() {
        try {
            FileOutputStream fos = new FileOutputStream("d://wuxi.D//一阶段项目//消费集合.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(consumInfo);
            System.out.println("数据更新成功!!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void menu2() {
        while (true) {
            System.out.println("===========中国电信用户菜单===========");
            System.out.println("1.本月账单查询\t2.套餐余量查询\t3.打印消费订单\t4.套餐变更\t5.办理退网");
            System.out.println("请选择相应的操作(输入其它将返回上一级)");
            String n = sc.next();
            if (n.equals("1")) {
                showBill();
            } else if (n.equals("2")) {
                System.out.println(sp.showInfo());
            } else if (n.equals("3")) {
                printAll();
            } else if (n.equals("4")) {
                changeService();
            } else if (n.equals("5")) {
                outInternet();
                break;
            } else break;
        }
    }

    private static void changeService() {
        System.out.println("请选择购买的套餐(请输入1-3)");
        System.out.println("1.话痨套餐\t2.超人套餐\t3.网虫套餐");
        int n = 0;
        while (true) {
            try {
                n = sc.nextInt();
                if (n < 1 || n > 3) {
                    System.out.println("输入错误,请输入1-3");
                    continue;
                }
                if (mc.getSerPackage().price == spList.get(n - 1).price) {
                    System.out.println("你已经购买了此套餐,请换其他套餐!");
                    continue;
                }
                break;
            } catch (Exception e) {
                System.out.println("输入错误,请输入数字1-3");
                sc.next(); // 清除错误的输入
            }
        }
        buyService(n);
    }

    public static void outInternet() {
        if (consumInfo.containsKey(mc.getCardNumber())) consumInfo.remove(mc.getCardNumber());
        if (card.containsKey(mc.getCardNumber())) card.remove(mc.getCardNumber());
        File f = new File("d://wuxi.D//一阶段项目//" + mc.getCardNumber() + "消费清单.txt");
        if (f.exists()) f.delete();
        System.out.println("退网成功");
        outputCard();
        outputMapConsum();
    }

    public static void showBill() {
        if (card.containsKey(mc.getCardNumber())) {
            System.out.println("用户: " + mc.getUserName());
            System.out.println("本月消费金额: " + df.format(mc.getConsumAmount()) + "元");
            System.out.println("当前余额: " + df.format(mc.getMoney()) + "元");
            ServicePackage sp = mc.getSerPackage();
            System.out.println(sp.showInfo());
        } else {
            System.out.println("电话号码不存在");
        }

    }

    public static String[] randomPhone() {
        String[] phones = new String[9];
        for (int i = 0; i < phones.length; i++) {
            StringBuilder sb = new StringBuilder("159");
            for (int j = 0; j < 8; j++) {
                sb.append(r.nextInt(10));
            }
            phones[i] = String.valueOf(sb);
        }
        return phones;
    }

}